package cn.cvs.controller;

import cn.cvs.entity.Supplier;
import cn.cvs.entity.SysUser;
import cn.cvs.service.supplier.SupplierService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 供货商模块控制器
 */
@Controller
@RequestMapping("/sys/supplier")
public class SupplierController {

    Logger logger = Logger.getLogger(SupplierController.class);
    @Autowired
    private SupplierService supplierService;

    /**
     * 查询所有供货商
     * @return
     */
    @GetMapping(value = "/simpleList",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public List<Supplier> getSupplierList(){
        List<Supplier> simpleList = null;
        try {
            simpleList = supplierService.getList();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return simpleList;
    }

    /**
     * 分页查询供货商数据
     * @param model
     * @param querySupCode
     * @param querySupName
     * @param pageIndex
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/list")
    public String getSupplierList(Model model
            ,@RequestParam(value="querySupCode",required=false) String querySupCode
            ,@RequestParam(value="querySupName",required=false) String querySupName
            ,@RequestParam(value="pageIndex",defaultValue = "1") Integer pageIndex)throws Exception{
        logger.info("参数【querySupCode】的值为: " + querySupCode);
        logger.info("参数【querySupName】的值为: " + querySupName);
        logger.info("参数【pageIndex】的值为: " + pageIndex);
        List<Supplier> supplierList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;

        //总数量（表）
        int totalCount	= supplierService.getCount(querySupCode,querySupName);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(pageIndex);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if(pageIndex > totalPageCount){
            pageIndex = totalPageCount;
        }
        supplierList = supplierService.getList(querySupName,querySupCode,pageIndex, pageSize);
        model.addAttribute("supplierList", supplierList);
        model.addAttribute("querySupCode", querySupCode);
        model.addAttribute("querySupName", querySupName);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", pageIndex);
        return "supplier/list";
    }

    /**
     * 跳转道添加供应商页面
     * @param supplier
     * @return
     */
	/*@GetMapping("/toAdd")
	public String add(Supplier supplier,Model model){
		model.addAttribute("supplier", supplier);
		return "supplier/add";
	}*/

    /**
     * 跳转道添加供应商页面
     * @param supplier
     * @return
     */
    @GetMapping("/toAdd")
    public String add(@ModelAttribute("supplier") Supplier supplier){
        logger.info("跳转道添加供应商页面");
        return "supplier/add";
    }

    /**
     * 添加供货商
     * @param supplier
     * @param session
     * @return
     */
	/*@PostMapping("/add")
	public String add(Supplier supplier,HttpSession session){
		logger.info("添加供货商信息");
		supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
		supplier.setCreatedTime(new Date());
		if(supplierService.add(supplier)){
			return "redirect:/supplier/list";
		}
		return "supplier/add";
	}*/
    /**
     * 添加用户信息，包含文件上传
     * @param supplier
     * @param session
     * @param request
     * @param companyLicPic
     * @return
     */
	/*@PostMapping("/add")
	public String add(Supplier supplier,HttpSession session,HttpServletRequest request,
								  @RequestParam(value ="companyLicPic", required = false) MultipartFile companyLicPic){
		String companyLicPicPath = null;
		//判断文件是否为空
		if(!companyLicPic.isEmpty()){
			String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
			String oldFileName = companyLicPic.getOriginalFilename();//原文件名
			String prefix= FilenameUtils.getExtension(oldFileName);//原文件后缀
			int filesize = 500000;
			if(companyLicPic.getSize() >  filesize){//上传大小不得超过 500k
				request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
				return "supplier/add";
			}else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
				String fileName = System.currentTimeMillis()+
						RandomUtils.nextInt(1000000)+"_Personal.jpg";
				File targetFile = new File(path, fileName);
				if(!targetFile.exists()){
					targetFile.mkdirs();
				}
				//保存
				try {
					companyLicPic.transferTo(targetFile);
				} catch (Exception e) {
					e.printStackTrace();
					request.setAttribute("uploadFileError", " * 上传失败！");
					return "supplier/add";
				}
				companyLicPicPath = path+File.separator+fileName;
			}else{
				request.setAttribute("uploadFileError", " * 上传图片格式不正确");
				return "supplier/add";
			}
		}
		supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
		supplier.setCompanyLicPicPath(companyLicPicPath);
		if(supplierService.add(supplier)){
			return "redirect:/supplier/list";
		}
		return "supplier/add";
	}*/

    /**
     * 添加用户信息，包含多文件上传
     * @param supplier
     * @param session
     * @param request
     * @param attachs
     * @return
     */
    @PostMapping("/add")
    public String add(Supplier supplier, HttpSession session, HttpServletRequest request
            , @RequestParam(value ="attachs", required = false) MultipartFile[] attachs){
        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        logger.info("uploadFile path ============== > "+path);
        for(int i = 0;i < attachs.length ;i++){
            MultipartFile attach = attachs[i];
            if(!attach.isEmpty()){
                if(i == 0){
                    errorInfo = "uploadFileError";
                }else if(i == 1){
                    errorInfo = "uploadOcError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                String prefix= FilenameUtils.getExtension(oldFileName);//原文件后缀
                int filesize = 500000;
                if(attach.getSize() >  filesize){//上传大小不得超过 500k
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                    String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";
                    logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }
                    if(i == 0){
                        companyLicPicPath = path+File.separator+fileName;
                    }else if(i == 1){
                        orgCodePicPath = path+File.separator+fileName;
                    }
                    logger.debug("companyLicPicPath: " + companyLicPicPath);
                    logger.debug("orgCodePicPath: " + orgCodePicPath);

                }else{
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if(flag){
            try {
                supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
                supplier.setCompanyLicPicPath(companyLicPicPath);
                supplier.setOrgCodePicPath(orgCodePicPath);
                if(supplierService.add(supplier)){
                    return "redirect:/sys/supplier/list";
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error("保存供货商信息失败");
            }
        }
        /*supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        supplier.setCompanyLicPicPath(companyLicPicPath);
        supplier.setOrgCodePicPath(orgCodePicPath);
        if(supplierService.add(supplier)){
            return "redirect:/supplier/list";
        }*/
        return "supplier/add";
    }


    /**
     * 查询供货商详情
     * @param id
     * @param model
     * @return
     */
	/*@GetMapping("/view/{id}")
	public String view(@PathVariable Integer id,Model model)throws Exception{
		logger.debug("view id===================== "+id);
		Supplier supplier = supplierService.getById(id);
		model.addAttribute(supplier);
		return "supplier/view";
	}*/

    /**
     * 跳转道修改供货商信息页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/toUpdate/{id}")
    public String toUpdate(@PathVariable Integer id,Model model)throws Exception{
        Supplier supplier = supplierService.getById(id);
        model.addAttribute(supplier);
        return "supplier/update";
    }

    /**
     * 修改供货商信息
     * @param supplier
     * @param session
     * @return
     */
    @PostMapping("/update")
    public String update(Supplier supplier,HttpSession session)throws Exception{
        logger.debug("修改供货商信息supplier:" + supplier);
        supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if(supplierService.update(supplier)){
            return "redirect:/sys/supplier/list";
        }
        return "supplier/update";
    }

    /**
     * 查询供货商详情
     * @param id
     * @param model
     * @param request
     * @return
     */
    @GetMapping("/view/{id}")
    public String view(@PathVariable Integer id,Model model,HttpServletRequest request)throws Exception{
        logger.debug("view id===================== "+id);
        Supplier supplier = supplierService.getById(id);

        if(supplier.getCompanyLicPicPath() != null && !"".equals(supplier.getCompanyLicPicPath())){
            String[] paths = supplier.getCompanyLicPicPath().split("\\"+File.separator);
            logger.debug("view companyLicPicPath paths[paths.length-1]============ " + paths[paths.length-1]);
            supplier.setCompanyLicPicPath(request.getContextPath()+"/statics/uploadfiles/"+paths[paths.length-1]);
        }
        if(supplier.getOrgCodePicPath() != null && !"".equals(supplier.getOrgCodePicPath())){
            String[] paths = supplier.getOrgCodePicPath().split("\\"+File.separator);
            logger.debug("view orgCodePicPath paths[paths.length-1]============ " + paths[paths.length-1]);
            supplier.setOrgCodePicPath(request.getContextPath()+"/statics/uploadfiles/"+paths[paths.length-1]);
        }
        model.addAttribute(supplier);
        return "supplier/view";
    }


    /**
     * 异步删除供货商
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable(required = true) Integer id){
        logger.debug("删除供货商 proid ===================== "+id);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        boolean flag = false;
        try {
            flag = supplierService.deleteById(id);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(flag){//删除成功
            resultMap.put("delResult", "true");
        }else{//删除失败
            resultMap.put("delResult", "false");
        }
        return resultMap;
    }
}
